package efu.nf.like.common.confirm;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.ReturnedMessage;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;

import java.util.UUID;

/**
 * @author lwj
 * @create 2025-10-15-9:26
 */
@Component
@Slf4j
@RequiredArgsConstructor
public class RabbitManager {
    private final RabbitTemplate rabbitTemplate;

    /**
     * 发送消息给消息队列
     * @param exchange 交换机名称
     * @param routingKey 路由键
     * @param callbackBeanName 回调业务实现类 bean 的名称
     * @param data 发送的数据
     */
    public<T> void send(String exchange, String routingKey, String callbackBeanName, T data) {
        try {
            // 创建消息的唯一ID
            CorrelationData cdata = new CorrelationData(UUID.randomUUID().toString());
            // 将投递的数据转换为 byte[]
            byte[] bytes = new ObjectMapper().writeValueAsBytes(data);
            // 将 bytes 封装为 Message 对象
            Message message = new Message(bytes);
            // 创建一个投递失败时返回的消息对象
            ReturnedMessage returnedMessage = new ReturnedMessage(message,
                    0,
                    callbackBeanName,
                    exchange,routingKey);
            // 将 ReturnedMessage 保存到 cdata 中
            cdata.setReturned(returnedMessage);
            // 投递消息
            rabbitTemplate.convertAndSend(exchange, routingKey, data, cdata);
        } catch (Exception e) {
            log.info("序列化Bytes[]失败：{}", e.getMessage());
            throw new RuntimeException(e);
        }
    }
}
